package com.iuie.ns.frame.utils.httpclients;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iuie.ns.frame.exception.ServiceException;
import com.iuie.ns.frame.utils.StringUtils;

/**
 * http Get 请求实现
 * @author liujie
 * @date 2018年6月2日下午3:24:38
 */
class HttpGetRequest implements IHttpRequest{
	
	private static final Logger logger = LoggerFactory.getLogger(HttpGetRequest.class);

	@Override
	public HttpResult send(HttpParams params) {
		try {
			@SuppressWarnings("unchecked")
			Map<String, Object> mParams = (Map<String, Object>) params.params();
			String url = params.url();
			
			if (StringUtils.isBlank(url)) {
				throw new ServiceException("ERR: httpGet请求失败，URL为空！");
			}
			
			// 拼接参数
			if (mParams != null && !mParams.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>(mParams.size());
				for (String key : mParams.keySet()) {
					pairs.add(new BasicNameValuePair(key, mParams.get(key).toString()));
				}
				if (url.contains("?")) {
					url += "&" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, params.charset()));
				} else {
					url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, params.charset()));
				}
			}
			
			// 设置HTTP请求头
			Map<String, String> headers = params.headers();
			headers.put("Accept", "*/*");
			headers.put("Accept-Encoding", "gzip, deflate, sdch");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("Content-Type", params.contentType().value());
			
			HttpGet httpGet = new HttpGet(url);
			Iterator<Entry<String, String>> it = headers.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, String> en = it.next();
				httpGet.setHeader(en.getKey(), en.getValue());
			}
			
			// 设置超时时间
			RequestConfig config = RequestConfig.custom()
				.setConnectTimeout(params.connectTimeout())
				.setSocketTimeout(params.socketTimeout()).build();
			httpGet.setConfig(config);
			
			// 发送httpGet请求
			CloseableHttpClient client = HttpClients.createDefault();
			CloseableHttpResponse resp = null;
			try {
				resp = client.execute(httpGet);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				throw new ServiceException("httpGet请求失败，UnsupportedEncodingException");
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				throw new ServiceException("httpGet请求失败，ClientProtocolException");
			} catch (IOException e) {
				e.printStackTrace();
				throw new ServiceException("httpGet请求失败，IOException");
			}
			
			// 获取并返回响应信息
			return new HttpResult(resp.getEntity(), client, resp);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("ERR:执行httpPost请求异常<br>url={}, 参数={}", params.url(), params.params());
			throw new ServiceException("ERR:执行httpGet请求异常<br>url=" + params.url());
		}
	}

}
